package threadlocal_test;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Ajie
 * @date 2021-03-17
 * @function 仿写ThreadLocal 核心逻辑
 * http://threadlocal.cn
 */
public class MyThreadLocal {

    private final ConcurrentHashMap threadLocalMap = new ConcurrentHashMap<>();

    public void set(Object newValue) {

/*        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);*/

        threadLocalMap.put(Thread.currentThread(), newValue);
    }

    public Object get() {
        /*Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();*/

        Object o = threadLocalMap.get(Thread.currentThread());

        if (o == null && !threadLocalMap.containsKey(this)) {

            o = initialValue();

            threadLocalMap.put(Thread.currentThread(), o);

        }
        return o;

    }

    public void remove() {
        threadLocalMap.remove(Thread.currentThread());
    }

    public Object initialValue() {
        return null;
    }

}
